import { useState } from 'react';
import { useGameStore } from '../../store/gameStore';
import { Character, GamePhase } from '../../types';
import { allCharacters } from '../../data/characters';

export default function CharacterSelect() {
  const game = useGameStore(state => state.game);
  const actions = useGameStore(state => state.actions);
  
  const [playerNames, setPlayerNames] = useState<string[]>(
    Array(game?.config.playerCount || 2).fill('').map((_, i) => `玩家${i + 1}`)
  );
  const [selectedCharacters, setSelectedCharacters] = useState<(Character | null)[]>(
    Array(game?.config.playerCount || 2).fill(null)
  );
  const [currentPlayerIndex, setCurrentPlayerIndex] = useState(0);

  const handleSelectCharacter = (character: Character) => {
    const newSelected = [...selectedCharacters];
    newSelected[currentPlayerIndex] = character;
    setSelectedCharacters(newSelected);

    if (currentPlayerIndex < (game?.config.playerCount || 2) - 1) {
      setCurrentPlayerIndex(currentPlayerIndex + 1);
    }
  };

  const handleStart = () => {
    if (!game) return;

    // 为每个玩家添加到游戏
    selectedCharacters.forEach((character, index) => {
      if (character) {
        actions.joinGame(game.id, playerNames[index], character);
      }
    });

    // 开始游戏
    setTimeout(() => {
      useGameStore.setState(state => ({
        game: state.game ? {
          ...state.game,
          phase: GamePhase.PLAYING,
        } : null,
      }));
      actions.startGame();
    }, 100);
  };

  const allSelected = selectedCharacters.every(c => c !== null);

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl p-8 max-w-6xl w-full">
        <h1 className="text-3xl font-bold text-center mb-2 text-purple-600">
          选择角色
        </h1>
        <p className="text-center text-gray-600 mb-8">
          {currentPlayerIndex < (game?.config.playerCount || 2) 
            ? `${playerNames[currentPlayerIndex]} 请选择角色`
            : '所有玩家已选择完毕'}
        </p>

        {/* 角色卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-8">
          {allCharacters.map(character => {
            const isSelected = selectedCharacters.includes(character);
            const isCurrentSelection = selectedCharacters[currentPlayerIndex] === character;

            return (
              <button
                key={character.id}
                onClick={() => !allSelected && handleSelectCharacter(character)}
                disabled={allSelected}
                className={`p-6 rounded-xl border-2 transition-all text-left ${
                  isCurrentSelection
                    ? 'border-purple-600 bg-purple-50'
                    : isSelected
                    ? 'border-gray-300 bg-gray-50 opacity-50'
                    : 'border-gray-200 hover:border-purple-400 hover:shadow-lg'
                } ${allSelected ? 'cursor-not-allowed' : 'cursor-pointer'}`}
              >
                <div className="text-4xl mb-2">{character.avatar}</div>
                <h3 className="font-bold text-lg mb-1">{character.name}</h3>
                <p className="text-sm text-gray-600 mb-3">{character.description}</p>
                
                <div className="space-y-2 text-sm">
                  <div>
                    <span className="font-semibold text-blue-600">被动：</span>
                    <span className="text-gray-700"> {character.passiveAbility.name}</span>
                  </div>
                  <div>
                    <span className="font-semibold text-purple-600">主动：</span>
                    <span className="text-gray-700"> {character.activeAbility.name}</span>
                  </div>
                </div>

                {isSelected && (
                  <div className="mt-3 text-sm font-semibold text-purple-600">
                    ✓ 已被选择
                  </div>
                )}
              </button>
            );
          })}
        </div>

        {/* 已选择的玩家 */}
        <div className="mb-6">
          <h3 className="font-semibold mb-3">已选择的玩家：</h3>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
            {selectedCharacters.map((character, index) => (
              <div
                key={index}
                className={`p-3 rounded-lg border ${
                  character ? 'border-purple-300 bg-purple-50' : 'border-gray-200 bg-gray-50'
                }`}
              >
                <div className="text-sm font-semibold mb-1">{playerNames[index]}</div>
                {character ? (
                  <div className="flex items-center gap-2">
                    <span className="text-2xl">{character.avatar}</span>
                    <span className="text-sm">{character.name}</span>
                  </div>
                ) : (
                  <div className="text-sm text-gray-400">未选择</div>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* 开始按钮 */}
        <button
          onClick={handleStart}
          disabled={!allSelected}
          className={`w-full py-3 px-6 rounded-lg font-semibold transition-colors ${
            allSelected
              ? 'bg-purple-600 text-white hover:bg-purple-700'
              : 'bg-gray-300 text-gray-500 cursor-not-allowed'
          }`}
        >
          {allSelected ? '开始游戏' : '请完成角色选择'}
        </button>
      </div>
    </div>
  );
}
